/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean;

import Merlion.CRM.entity.BillingAddressEntity;
import Merlion.CRM.entity.ClientEntity;
import Merlion.CRM.entity.LineEntryEntity;

import Merlion.CRM.entity.PricebookEntity;
import Merlion.CRM.bean.SalesLeadModuleRemote;
import Merlion.CRM.bean.SalesOrderProcessingModuleRemote;
import Merlion.CRM.entity.ShippingAddressEntity;
import Merlion.util.state.AddressState;
import Merlion.util.state.ClientState;
import Merlion.util.state.ContactState;
import Merlion.util.state.LineEntryState;
import Merlion.util.state.ProductState;
import Merlion.util.state.SalesDocumentState;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author anindya
 */
@ManagedBean(name = "PurchaseOrderManagedBean")
@ViewScoped
public class PurchaseOrderManagedBean implements Serializable {

    private LineEntryState lineEntry = new LineEntryState();
    private List<LineEntryState> lineEntryList = new ArrayList<LineEntryState>();
    private Long quotationInput;
    private Date dateIssued;
    private String billingStreet;
    private String billingState;
    private String billingCity;
    private String billingCode;
    private String billingCountry;
    private String shippingStreet;
    private String shippingState;
    private String shippingCity;
    private String shippingCode;
    private String shippingCountry;
    private String soName;
    private String soDesc;
    private Long purchaseOrderID;
    private String purchaseOrderId;
    private SalesDocumentState newPurchaseOrder;
    private List<SalesDocumentState> purchaseOrderList;
    private SalesDocumentState selectedPurchaseOrder;
    private SalesDocumentState[] selectedPurchaseOrders;
    private ClientEntity client;
  
    private List<LineEntryState> productList;
    private SalesDocumentState selectedViewPurchaseOrder;
    private List<ClientState> clientList;
    private List<SalesDocumentState> quotationList;
    private List<LineEntryState> selectedProductList;
    private boolean editMode;
    private Date dueDate;

    private List<SalesDocumentState> convertedPurchaseOrders;
    private Long productId;
    private int quantity;
    private double listPrice;
    private String type;
    private PricebookEntity pricebook;
    private List<PricebookEntity> pricebookList;
    private double totalPrice;
    private String pricingType;
    private String docName;
    private String description;
    private List<AddressState> billingAddress;
    private List<AddressState> shippingAddress;
    private List<ContactState> contactList;
    private List<ContactState> selectedContactList;
    @EJB
    private SalesOrderProcessingModuleRemote sop;
    @EJB
    private SalesLeadModuleRemote smb;

    public List<ContactState> getSelectedContactList() {
        if (selectedContactList == null) {
            if (selectedViewPurchaseOrder != null) {
                selectedContactList = smb.viewContactsForClients(selectedViewPurchaseOrder.getClientId());
            }
        }
        return selectedContactList;
    }

    public void setSelectedContactList(List<ContactState> selectedContactList) {
        this.selectedContactList = selectedContactList;
    }

    public SalesDocumentState getNewPurchaseOrder() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (newPurchaseOrder == null) {
            newPurchaseOrder = new SalesDocumentState();
        }
        return newPurchaseOrder;
    }

    public void setNewPurchaseOrder(SalesDocumentState newPurchaseOrder) {
        this.newPurchaseOrder = newPurchaseOrder;
    }

    public String reinit() {
        lineEntry = new LineEntryState();
        return null;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }


    public List<LineEntryState> getProductList() {

        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        System.out.println("Get Product List");               
        return productList;
    }

    public void setProductList(List<LineEntryState> productList) {
        this.productList = productList;
    }

    public List<SalesDocumentState> getQuotationList() {
        if (quotationList == null) {
            quotationList = sop.viewQuotationsforPO();
        }
        return quotationList;
    }

    public void setQuotationList(List<SalesDocumentState> quotationList) {
        this.quotationList = quotationList;
    }

    public List<LineEntryState> getSelectedProductList() {
        return selectedProductList;
    }

    public void setSelectedProductList(List<LineEntryState> selectedProductList) {
        this.selectedProductList = selectedProductList;
    }

    public List<ClientState> getClientList() {
        if (clientList == null) {
            clientList = smb.viewClients();
        }
        return clientList;
    }

    public void setClientList(List<ClientState> clientList) {
        this.clientList = clientList;
    }

    public String getBillingCity() {
        return billingCity;
    }

    public void setBillingCity(String billingCity) {
        if (billingCity.equals("")) {
            billingCity = "-";
        }
        this.billingCity = billingCity;
    }

    public String getBillingCode() {
        return billingCode;
    }

    public void setBillingCode(String billingCode) {
        if (billingCode.equals("")) {
            billingCode = "-";
        }
        this.billingCode = billingCode;
    }

    public String getBillingCountry() {
        return billingCountry;
    }

    public void setBillingCountry(String billingCountry) {
        if (billingCountry.equals("")) {
            billingCountry = "-";
        }
        this.billingCountry = billingCountry;
    }

    public String getBillingState() {
        return billingState;
    }

    public void setBillingState(String billingState) {
        if (billingState.equals("")) {
            billingState = "-";
        }
        this.billingState = billingState;
    }

    public String getBillingStreet() {
        return billingStreet;
    }

    public void setBillingStreet(String billingStreet) {
        if (billingStreet.equals("")) {
            billingStreet = "-";
        }
        this.billingStreet = billingStreet;
    }

    public String getShippingCity() {
        return shippingCity;
    }

    public void setShippingCity(String shippingCity) {
        if (shippingCity.equals("")) {
            shippingCity = "-";
        }
        this.shippingCity = shippingCity;
    }

    public String getShippingCode() {
        return shippingCode;
    }

    public void setShippingCode(String shippingCode) {
        if (shippingCode.equals("")) {
            shippingCode = "-";
        }
        this.shippingCode = shippingCode;
    }

    public String getShippingCountry() {
        return shippingCountry;
    }

    public void setShippingCountry(String shippingCountry) {
        if (shippingCountry.equals("")) {
            shippingCountry = "-";
        }
        this.shippingCountry = shippingCountry;
    }

    public String getShippingState() {
        return shippingState;
    }

    public void setShippingState(String shippingState) {
        if (shippingState.equals("")) {
            shippingState = "-";
        }
        this.shippingState = shippingState;
    }

    public String getShippingStreet() {
        return shippingStreet;
    }

    public void setShippingStreet(String shippingStreet) {
        if (shippingStreet.equals("")) {
            shippingStreet = "-";
        }
        this.shippingStreet = shippingStreet;
    }

    public SalesDocumentState getSelectedViewPurchaseOrder() {
        return selectedViewPurchaseOrder;
    }

    public void setSelectedViewPurchaseOrder(SalesDocumentState selectedViewPurchaseOrder) {
        this.selectedViewPurchaseOrder = selectedViewPurchaseOrder;
        if (selectedViewPurchaseOrder != null) {
            System.out.println("View PurchaseOrder NOT NULL");
        }
        this.selectedViewPurchaseOrder = selectedViewPurchaseOrder;
        System.out.println("ID : " + selectedViewPurchaseOrder.getId());
        // this.setSelectedViewQuotationID(selectedViewQuotation.getId());

        //FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectedViewInquiryID",selectedViewInquiryID);
        selectedProductList = sop.viewProductListforSalesDocument(selectedViewPurchaseOrder.getId());
        this.setSelectedProductList(selectedProductList);
    }

    public void convertedInitView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (convertedPurchaseOrders == null) {
            convertedPurchaseOrders = sop.viewConvertedPurchaseOrders();
        }
    }

    public List<SalesDocumentState> getConvertedPurchaseOrders() {
        return convertedPurchaseOrders;
    }

    public void setConvertedPurchaseOrders(List<SalesDocumentState> convertedPurchaseOrders) {
        this.convertedPurchaseOrders = convertedPurchaseOrders;
    }

    public void initView2(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (purchaseOrderList == null) {
            purchaseOrderList = sop.viewPurchaseOrders();
        }
    }

    public void initView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public PurchaseOrderManagedBean() {
        lineEntry = new LineEntryState();
    }

    public LineEntryState getLineEntry() {
        return lineEntry;
    }

    public void setLineEntry(LineEntryState lineEntry) {
        this.lineEntry = lineEntry;
    }

    public List<LineEntryState> getLineEntryList() {
        System.out.println("GET LINE ENTRY LIST");
        return lineEntryList;
    }

    public Date getDateIssued() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        return dateIssued;
    }

    public void setDateIssued(Date dateIssued) {
        this.dateIssued = dateIssued;
    }

    public String getDescription() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDocName() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        return docName;
    }

    public void setDocName(String docName) {
        this.docName = docName;
    }

    public Date getDueDate() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        return dueDate;
    }

    public void setDueDate(Date dueDate) {
        this.dueDate = dueDate;
    }

    public void setLineEntryList(List<LineEntryState> lineEntryList) {
        System.out.println("SET LINE ENTRY LIST");
        this.lineEntryList = lineEntryList;
    }

    public void addPurchaseOrder(ActionEvent event) {

        System.out.println(":::WEB::: Add Purchase Order2");

        String status = newPurchaseOrder.getStatus();
        Date cDateIssued = newPurchaseOrder.getDateIssued();
        Long clientId = newPurchaseOrder.getClientId();
        Long contactId = newPurchaseOrder.getContactId();

        String cDescription = newPurchaseOrder.getDescription();
        String cDocName = newPurchaseOrder.getDocumentName();
        String shippingMethod = newPurchaseOrder.getShippingMethod();
        String shippingRule = newPurchaseOrder.getShippingRule();
        Date cDueDate = newPurchaseOrder.getDueDate();
        String invoiceRule = newPurchaseOrder.getInvoiceRule();
        String paymentMethod = newPurchaseOrder.getPaymentMethod();
        String freightCostRule = newPurchaseOrder.getFreightCostRule();
        String currency = newPurchaseOrder.getCurrency();
        String epricingType = newPurchaseOrder.getPricingType();



        String billStreet = newPurchaseOrder.getBillingStreet();
        String billState = newPurchaseOrder.getBillingState();
        String billCity = newPurchaseOrder.getBillingCity();
        String billCode = newPurchaseOrder.getBillingCode();
        String billCountry = newPurchaseOrder.getBillingCountry();


        String shipStreet = newPurchaseOrder.getShippingStreet();
        String shipState = newPurchaseOrder.getShippingState();
        String shipCity = newPurchaseOrder.getShippingCity();
        String shipCode = newPurchaseOrder.getShippingCode();
        String shipCountry = newPurchaseOrder.getShippingCountry();

        ClientState clState = smb.searchClient(clientId);
        Long billingId = Long.parseLong("0");
        Long shippingId = Long.parseLong("0");

        if (clState.getClientType().equals("CU")) {

            if (newPurchaseOrder.getBillingId() != null) {
                System.out.println("Billing ID not null!");
                billingId = newPurchaseOrder.getBillingId();
                smb.editBillingAddress(billingId, billStreet, billCity, billState, billCode, billCountry);
            }

            if (newPurchaseOrder.getShippingId() != null) {
                System.out.println("Shipping ID not null!");
                shippingId = newPurchaseOrder.getShippingId();
                smb.editShippingAddress(shippingId, shipStreet, shipCity, shipState, shipCode, shipCountry);
            }
        } else {
            BillingAddressEntity ba = smb.addBillingAddress(billStreet, billCity, billState, billCode, billCountry);
            ShippingAddressEntity sa = smb.addShippingAddress(shipStreet, shipCity, shipState, shipCode, shipCountry);
            billingId = ba.getId();
            shippingId = sa.getId();
        }

        System.out.println("Customer ID is : " + newPurchaseOrder.getClientId());

        if (!lineEntryList.isEmpty()) {
            System.out.println("Products not null");
            System.out.println("ID is : " + lineEntryList.get(0).getId());
        }
        System.out.println(":::WEB::: Calling addPurchaseOrder()");


        sop.addPurchaseOrder(cDateIssued, clientId, contactId, lineEntryList, quotationInput, billingId, shippingId,
                cDescription, cDueDate, cDocName, shippingMethod, shippingRule,
                invoiceRule, paymentMethod, freightCostRule, currency, epricingType);
        System.out.println(":::WEB::: Add Purchase Order 2 done");

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("purchaseOrderSuccessfulRegistration.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void onEditRow(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Row");
        SalesDocumentState eDocument = (SalesDocumentState) event.getObject();
        if (eDocument != null) {


            System.out.println(":::WEB::: Edited document not null");
      
            String eStatus = eDocument.getStatus();
            Date eDateIssued = eDocument.getDateIssued();
            Long eClientId = eDocument.getClientId();
            Long ePoId = eDocument.getId();
            System.out.println("Purchase Order ID " + ePoId);
            Long eQuotationID = eDocument.getQuotationID();
            Long eContactID = eDocument.getContactId();

            Long eBillId = eDocument.getBillingId();
            String eBillStreet = eDocument.getBillingStreet();
            String eBillState = eDocument.getBillingState();
            String eBillCity = eDocument.getBillingCity();
            String eBillCode = eDocument.getBillingCode();
            String eBillCountry = eDocument.getBillingCountry();
            smb.editBillingAddress(eBillId, eBillStreet, eBillCity, eBillState, eBillCode, eBillCountry);

            Long eShipId = eDocument.getShippingId();
            String eShipStreet = eDocument.getShippingStreet();
            String eShipState = eDocument.getShippingState();
            String eShipCity = eDocument.getShippingCity();
            String eShipCode = eDocument.getShippingCode();
            String eShipCountry = eDocument.getShippingCountry();

            smb.editShippingAddress(eShipId, eShipStreet, eShipCity, eShipState, eShipCode, eShipCountry);

            String eDesc = eDocument.getDescription();
            String eDocName = eDocument.getDocumentName();
            String eShippingMethod = eDocument.getShippingMethod();
            String eShippingRule = eDocument.getShippingRule();
            Date eDueDate = eDocument.getDueDate();
            String eInvoiceRule = eDocument.getInvoiceRule();
            String ePaymentMethod = eDocument.getPaymentMethod();
            String eFreightCostRule = eDocument.getFreightCostRule();
            String eCurrency = eDocument.getCurrency();

            System.out.println(":::WEB::: Calling Edit Purchase Order");
            sop.editPurchaseOrder(ePoId, eDateIssued, eClientId, eContactID, eQuotationID, eStatus,
                    eDesc, eDueDate, eDocName, eShippingMethod, eShippingRule, eInvoiceRule,
                    ePaymentMethod, eFreightCostRule, eCurrency, eBillId, eShipId);
        } else {
            System.out.println(":::WEB::: Edited purchase order is null");
        }

    }

    public void deletePurchaseOrders() {
        System.out.println(":::WEB::: Delete Purchase Orders");

        if (selectedPurchaseOrders != null) {
            System.out.println(":::WEB::: If selected purchase orders not null");
            for (int i = 0; i < selectedPurchaseOrders.length; i++) {
                System.out.println("selectedPurchaseOrders i: " + i + " - " + selectedPurchaseOrders[i].getId());
                sop.deletePurchaseOrder(selectedPurchaseOrders[i].getId());
            }
        } else {
            System.out.println(":::WEB::: Selected purchaser orders are null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("purchaseOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void cancelDelete() {
        for (SalesDocumentState sdState : selectedPurchaseOrders) {
            sdState = null;
        }
        if (selectedPurchaseOrders == null) {
            System.out.println(":::WEB::: Deletion of Purchase Orders cancelled");

        } else {
            System.out.println(":::WEB::: Deletion of Purchase Orders are not cancelled");
        }

    }

    public void handleDocName() {
        if (docName != null) {
            System.out.println("handle doc name");
            newPurchaseOrder.setDocumentName(docName);
        }

    }

    public void handleDateIssued() {
        if (dateIssued != null) {
            System.out.println("Date issued set");
            newPurchaseOrder.setDateIssued(dateIssued);
        }
    }

    public void handleDueDate() {
        if (dueDate != null) {
            System.out.println("set due date");
            newPurchaseOrder.setDueDate(dueDate);
        }
    }

    public void handleDesc() {

        if (description != null) {
            newPurchaseOrder.setDescription(description);
        }
    }

    public void delete(ActionEvent Event) {

        System.out.println(":::WEB::: Delete Purchase Order");

        if (selectedPurchaseOrder != null) {
            System.out.println(":::WEB::: Selected Purchase Order not null");
            Long purchaseOrderId = selectedPurchaseOrder.getId();
            System.out.println(":::WEB::: Purchase Order ID is : " + purchaseOrderId);
            sop.deletePurchaseOrder(purchaseOrderId);
            System.out.println(":::WEB::: Deletion done");
        } else {
            System.out.println(":::WEB::: Selected Purchase Order is null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("purchaseOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public ClientEntity getClient() {
        return client;
    }

    public void setClient(ClientEntity client) {
        this.client = client;
    }

    public Long getPurchaseOrderID() {
        return purchaseOrderID;
    }

    public void setPurchaseOrderID(Long purchaseOrderID) {
        this.purchaseOrderID = purchaseOrderID;
    }

    public String getPurchaseOrderId() {
        return purchaseOrderId;
    }

    public void setPurchaseOrderId(String purchaseOrderId) {
        this.purchaseOrderId = purchaseOrderId;
    }


    public Long getQuotationInput() {
        return quotationInput;
    }

    public void setQuotationInput(Long quotationInput) {
        this.quotationInput = quotationInput;
    }

    public List<SalesDocumentState> getPurchaseOrderList() {
        return purchaseOrderList;
    }

    public void setPurchaseOrderList(List<SalesDocumentState> purchaseOrderList) {
        this.purchaseOrderList = purchaseOrderList;
    }

    public SalesDocumentState getSelectedPurchaseOrder() {
        return selectedPurchaseOrder;
    }

    public void setSelectedPurchaseOrder(SalesDocumentState selectedPurchaseOrder) {
        System.out.println(":::WEB::: SET SELECTED Purchase Order");
        this.selectedPurchaseOrder = selectedPurchaseOrder;
    }

    public SalesDocumentState[] getSelectedPurchaseOrders() {
        return selectedPurchaseOrders;
    }

    public void setSelectedPurchaseOrders(SalesDocumentState[] selectedPurchaseOrders) {
        System.out.println("::WEB::: SET SELECTED Purchase Orders");
        this.selectedPurchaseOrders = selectedPurchaseOrders;
    }


    public void save(ActionEvent event) {
        System.out.println(":::WEB::: Save Edit PO");

        Long cPoID = selectedViewPurchaseOrder.getId();
        Date cDateIssued = selectedViewPurchaseOrder.getDateIssued();
        Long cClientID = selectedViewPurchaseOrder.getClientId();
        Long cQuotationID = selectedViewPurchaseOrder.getQuotationID();
        String cStatus = selectedViewPurchaseOrder.getStatus();

        Long cBillId = selectedViewPurchaseOrder.getBillingId();
        String cBillStreet = selectedViewPurchaseOrder.getBillingStreet();
        String cBillState = selectedViewPurchaseOrder.getBillingState();
        String cBillCity = selectedViewPurchaseOrder.getBillingCity();
        String cBillCode = selectedViewPurchaseOrder.getBillingCode();
        String cBillCountry = selectedViewPurchaseOrder.getBillingCountry();

        smb.editBillingAddress(cBillId, cBillStreet, cBillCity, cBillState, cBillCode, cBillCountry);

        Long cShipId = selectedViewPurchaseOrder.getShippingId();
        String cShipStreet = selectedViewPurchaseOrder.getShippingStreet();
        String cShipState = selectedViewPurchaseOrder.getShippingState();
        String cShipCity = selectedViewPurchaseOrder.getShippingCity();
        String cShipCode = selectedViewPurchaseOrder.getShippingCode();
        String cShipCountry = selectedViewPurchaseOrder.getShippingCountry();

        smb.editShippingAddress(cShipId, cShipStreet, cShipCity, cShipState, cShipCode, cShipCountry);

        String cDescription = selectedViewPurchaseOrder.getDescription();
        String cDocName = selectedViewPurchaseOrder.getDocumentName();
        String cShippingMethod = selectedViewPurchaseOrder.getShippingMethod();
        String cShippingRule = selectedViewPurchaseOrder.getShippingRule();
        String cPaymentMethod = selectedViewPurchaseOrder.getPaymentMethod();
        String cInvoiceRule = selectedViewPurchaseOrder.getInvoiceRule();
        String cFreightCostRule = selectedViewPurchaseOrder.getFreightCostRule();
        String cCurrency = selectedViewPurchaseOrder.getCurrency();
        Date cDueDate = selectedViewPurchaseOrder.getDueDate();
        Long cContactId = selectedViewPurchaseOrder.getContactId();

        System.out.println("PO ID is :" + cPoID);
        System.out.println(":::WEB::: Calling edit PO");
        sop.editPurchaseOrder(cPoID, cDateIssued, cClientID, cContactId, cQuotationID, cStatus,
                cDescription, cDueDate, cDocName, cShippingMethod, cShippingRule, cInvoiceRule,
                cPaymentMethod, cFreightCostRule, cCurrency, cBillId, cShipId);

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("purchaseOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }


    }

    public String getSoDesc() {
        return soDesc;
    }

    public void setSoDesc(String soDesc) {
        this.soDesc = soDesc;
    }

    public String getSoName() {
        return soName;
    }

    public void setSoName(String soName) {
        this.soName = soName;
    }

    public void convertToSalesOrder(ActionEvent event) {
        if (selectedViewPurchaseOrder.getStatus().equals("Validated")) {
            Long cPoId = selectedViewPurchaseOrder.getId();


            sop.convertPurchaseOrderToSalesOrder(cPoId, soName, soDesc);

            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("purchaseOrders.xhtml");
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        } else {
            System.out.println("Status not approved!");
            FacesContext context = FacesContext.getCurrentInstance();

            context.addMessage(null, new FacesMessage("Purchase Order Conversion not successful!", "Status has not been validated."));

        }

    }

    public PricebookEntity getPricebook() {

        return pricebook;
    }

    public void setPricebook(PricebookEntity pricebook) {
        System.out.println("SET PRICEBOOK");

        this.pricebook = pricebook;

    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        System.out.println("Set total price");
        this.totalPrice = totalPrice;
    }

    public String getPricingType() {
        return pricingType;
    }

    public void setPricingType(String pricingType) {
        this.pricingType = pricingType;
    }

    public List<PricebookEntity> getPricebookList() {
        System.out.println("GET PRICEBOOK LIST");

        if (pricebookList == null) {
            // if (lineEntry.getProduct() == null) {
            System.out.println("GET from bean");
            pricebookList = sop.getPricebookList();
            // }
        }
        return pricebookList;
    }

    public void setPricebookList(List<PricebookEntity> pricebookList) {
        System.out.println("SET pricebook List");
        this.pricebookList = pricebookList;
    }

    public double getListPrice() {
        return listPrice;
    }

    public void setListPrice(double listPrice) {
        System.out.println("SET LIST PRICE");
        this.listPrice = listPrice;
    }

    public void handlePricebookChange() {
        System.out.println("HANDLE PRICEBOOK CHANGE");
        if (lineEntry.getPricebookId() != null) {
            System.out.println("Pricebook not null");
            System.out.println("Type " + type);
            System.out.println("quantity" + lineEntry.getQuantity());

            listPrice = sop.getListPrice(lineEntry.getQuantity(), type, lineEntry.getPricebookId());
            lineEntry.setPrice(listPrice);
            System.out.println(lineEntry.getPrice());
            double total = sop.getTotalPrice(lineEntry, pricingType);
            System.out.println("Total " + total);
            lineEntry.setTotalPrice(total);
        }
    }

    public void onRowEdit(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Row");
        LineEntryState eLine = (LineEntryState) event.getObject();
        int eQuantity = eLine.getQuantity();
        double newPrice = eLine.getPrice();
        eLine.setPrice(newPrice);
        eLine.setQuantity(eQuantity);
        double total = sop.getTotalPrice(eLine, pricingType);

        eLine.setTotalPrice(total);
   
    }

    public void handleProductChange() {
        System.out.println("HANDLE PRODUCT CHANGE");
        if (lineEntry.getItemId() != null) {
            List<PricebookEntity> list = sop.getPricebook(lineEntry.getItemId());
            System.out.println("Product is not empty");
            this.setPricebookList(list);
            ProductState product = sop.searchProduct(lineEntry.getItemId());
            lineEntry.setItemName(product.getItemName());
            lineEntry.setBasePrice(product.getPrice());
        }
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<AddressState> getBillingAddress() {
        if (billingAddress == null) {
            billingAddress = sop.getBillingAddressList();
        }
        return billingAddress;
    }

    public void setBillingAddress(List<AddressState> billingAddress) {
        this.billingAddress = billingAddress;
    }

    public List<AddressState> getShippingAddress() {
        if (shippingAddress == null) {
            shippingAddress = sop.getShippingAddressList();
        }
        return shippingAddress;
    }

    public void setShippingAddress(List<AddressState> shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    public List<ContactState> getContactList() {
        if (contactList == null) {
            contactList = smb.viewContacts();
        }
        return contactList;
    }

    public void setContactList(List<ContactState> contactList) {
        this.contactList = contactList;
    }

    public void handleClientChange() {
        System.out.println("Handle client change");
        if (newPurchaseOrder.getClientId() != null) {
            ClientState clState = smb.searchClient(newPurchaseOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);
            SalesDocumentState quotationState = sop.searchQuotation(quotationInput);
            Long contactId = quotationState.getContactId();

            if (clState.getClientType().equals("CU")) {
                System.out.println("Set billing and shipping address");
                List<AddressState> addressList = clState.getAddressList();

                List<AddressState> billingAddressList = new ArrayList<AddressState>();
                List<AddressState> shippingAddressList = new ArrayList<AddressState>();
                List<ContactState> cList = smb.viewContactsForClients(clState.getId());
                System.out.println(cList.size());
                for (Object o : addressList) {
                    AddressState as = (AddressState) o;
                    if (as.getType().equals("B")) {
                        billingAddressList.add(as);
                    } else if (as.getType().equals("S")) {
                        shippingAddressList.add(as);
                    }
                }

                this.setBillingAddress(billingAddressList);
                this.setShippingAddress(shippingAddressList);
                this.setContactList(cList);
               
            }
        } else {
            billingAddress = sop.getBillingAddressList();
            shippingAddress = sop.getShippingAddressList();
            contactList = smb.viewContacts();
            this.setBillingAddress(billingAddress);
            this.setShippingAddress(shippingAddress);
            this.setContactList(contactList);
        }
    }

    public void handlePriceChange() {
        System.out.println("Handle price change");
        if (lineEntry.getPrice() != 0) {
            System.out.println("Price " + lineEntry.getPrice());
            double total = sop.getTotalPrice(lineEntry, pricingType);
            lineEntry.setTotalPrice(total);
        }
    }

    public void handleSalesDocumentChange() {
        System.out.println("HANDLE SALES DOCUMENT CHANGE");
        if (quotationInput != null) {
            SalesDocumentState quotationState = sop.searchQuotation(quotationInput);
            Long salesDocClient = quotationState.getClientId();
            Long contactId = quotationState.getContactId();
            System.out.println("Sales doc client : " + salesDocClient);
            newPurchaseOrder.setClientId(salesDocClient);
          
            ClientState clState = smb.searchClient(newPurchaseOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);
            String pType = quotationState.getPricingType();
            this.setPricingType(pType);
            newPurchaseOrder.setPricingType(pType);

            handleClientChange();

            System.out.println("Getting line entry list from quotation");
            Collection<LineEntryEntity> collectionList = quotationState.getLineEntryList();
            List<LineEntryEntity> list = new ArrayList<LineEntryEntity>(collectionList);
            List<LineEntryState> newList = new ArrayList<LineEntryState>();
            for (Object o : list) {
                LineEntryEntity line = (LineEntryEntity) o;
                LineEntryState a = new LineEntryState();
                a.setBasePrice(line.getBasePrice());
                a.setItemId(line.getItemId());
                a.setTotalPrice(line.getTotalLinePrice());
                a.setQuantity(line.getQuantity());
                a.setPrice(line.getPrice());
                a.setPricebookId(line.getPricebookId());
                a.setIndicativeLeadTime(line.getLeadTime());
                a.setItemName(line.getItemName());
                lineEntryList.add(a);
                newList.add(a);
            }
            

            this.setProductList(newList);
            handleProductChange();
            handlePricebookChange();
            handlePriceChange();
         

        }
    }


    public void handleBillingAddressChange() {
        System.out.println("Handle billing Address Change");
        if (newPurchaseOrder.getBillingId() != null) {
            AddressState ba = sop.searchBillingAddress(newPurchaseOrder.getBillingId());
            newPurchaseOrder.setBillingStreet(ba.getStreet());
            newPurchaseOrder.setBillingCity(ba.getCity());
            newPurchaseOrder.setBillingState(ba.getState());
            newPurchaseOrder.setBillingCode(ba.getCode());
            newPurchaseOrder.setBillingCountry(ba.getCountry());
        }

    }

    public void handleShippingAddressChange() {
        System.out.println("Handle Shipping Address Change");
        System.out.println("shipping id" + newPurchaseOrder.getShippingId());
        if (newPurchaseOrder.getShippingId() != null) {
            AddressState sa = sop.searchShippingAddress(newPurchaseOrder.getShippingId());
            newPurchaseOrder.setShippingStreet(sa.getStreet());
            newPurchaseOrder.setShippingCity(sa.getCity());
            newPurchaseOrder.setShippingState(sa.getState());
            newPurchaseOrder.setShippingCode(sa.getCode());
            newPurchaseOrder.setShippingCountry(sa.getCountry());
        }

    }
}
